import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:ui' as ui;

import 'package:path_provider/path_provider.dart';

/// 加载本地资源图片
Widget loadAssetImage(String name, {double width, double height, BoxFit fit}) {
  return Image.asset(
    name,
    height: height,
    width: width,
    fit: fit,
  );
}

class ImgInfo {
  final double width;
  final double height;
  final double rate;
  ImgInfo(this.width, this.height, this.rate);
}

class ImgInformation {
  final double width;
  final double height;
  final double rate;
  ImgInformation(this.width, this.height, this.rate);
}

Future<ImgInformation> getImageRate(String type, String url) async {
  File imgFile;
  switch (type) {
    case 'file':
      imgFile = File(url);
  }
  var bytes = imgFile.readAsBytesSync();
  var sth = await decodeImageFromList(bytes);
  double height = sth.height.toDouble(); //获取图片的宽高
  double width = sth.width.toDouble(); //获取图片的宽高
  return ImgInformation(width, height, width / height);
}

class ImageCrop {
  static Future<ui.Image> _loadImge(url) async {
    ImageStream imageStream =
        FileImage(File(url)).resolve(ImageConfiguration());
    Completer<ui.Image> completer = Completer<ui.Image>();
    void imageListener(ImageInfo info, bool synchronousCall) {
      ui.Image image = info.image;
      completer.complete(image);
      imageStream.removeListener(ImageStreamListener(imageListener));
    }

    imageStream.addListener(ImageStreamListener(imageListener));
    return completer.future;
  }

  static Future<dynamic> clip(BuildContext context, String imgUrl, Size size,
      double top, double bottom, Function callBack) async {
    ui.Image uiImage;
    return _loadImge(imgUrl).then((image) {
      uiImage = image;
    }).whenComplete(() async {
      //将画板转化为图片
      ui.PictureRecorder recorder = ui.PictureRecorder();
      Canvas canvas = Canvas(recorder);
      // print(size.height);
      ImageClipper clipper = ImageClipper(uiImage, top: top, bottom: bottom);
      clipper.paint(canvas, size);
      ui.Image img = await recorder
          .endRecording()
          .toImage(size.width.floor(), size.height.floor());
      Directory appDocDir = await getApplicationDocumentsDirectory(); //获取
      String appDocPath = appDocDir.path;
      var pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
      String timestamp =
          DateTime.now().millisecondsSinceEpoch.toString() + 'youdi';
      final imageFile = File(path.join(appDocPath, '${timestamp}.png'));
      await imageFile.writeAsBytesSync(pngBytes.buffer.asInt8List());
      if (callBack is Function) {
        callBack(imageFile.path);
      }
    });
  }
}

/// 图片裁剪
class ImageClipper extends CustomPainter {
  final ui.Image image;
  final double left;
  final double top;
  final double right;
  final double bottom;

  ImageClipper(this.image,
      {this.left = 0,
      @required this.top,
      this.right = 1,
      @required this.bottom});
  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    Paint paint = Paint();
    canvas.drawImageRect(
        image,
        Rect.fromLTRB(
            0, top, image.width * 1.0, bottom), //图片上的的某一部分 inputRect 表示矩形的坐标
        Rect.fromLTWH(
            0, 0, size.width, size.height), // outputRect  在canvas上绘制的坐标，宽 高
        paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
